<!-- 文章管理 -->
<template>
    <div class="main-container article-mng">
        <header class="title">
            <h2>內容管理-當前欄目：{{columnName}}</h2>
            <router-link :to="hrefOfAddArticle" class="pull-right">{{nameOfAddArticle}}>></router-link>
        </header>
        <div class="content">
            <nav>
                <el-tree class="column-tree"
                    :filter-node-method="filterNode"
                    node-key="id"
                    :data="columnTreeData"
                    :props="defaultProps"
                    :default-expand-all="true"
                    :highlight-current="true"
                    :expand-on-click-node="false"
                    @node-click="handleTreeNodeClick"
                    :current-node-key="columnId">
                </el-tree>
            </nav>
            <section>
                <template v-if="!columnType">
                    <el-table :data="articleList" border>
                        <el-table-column label="文章標題" prop="title"></el-table-column>
                        <el-table-column label="所屬欄目" prop="columnName" width="150" align="center"></el-table-column>
                        <el-table-column label="操作" width="150" align="center">
                            <template scope="scope">
                                <el-button size="small" @click="handleEdit(scope.$index, scope.row)">編輯</el-button>
                                <el-button size="small" type="danger" @click="deleteArticle(scope.$index, scope.row)">刪除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                    <el-pagination
                        @size-change="handleSizeChange"
                        @current-change="handleCurrentChange"
                        :current-page="pager.pageNum"
                        :page-sizes="[10, 20, 50, 100]"
                        :page-size="pager.pageSize"
                        layout="total, sizes, prev, pager, next, jumper"
                        :total="pager.total">
                    </el-pagination>
                </template>
                <div v-else-if="columnType === 1">
                    <el-table
                        class="media-list"
                        :data="mediaList"
                        border
                        style="width: 100%">
                        <el-table-column
                            label="文件"
                            width="400">
                            <template scope="scope">
                                <template v-if="testPic(scope.row.fileName)">
                                    <img :src="scope.row.filePath">
                                </template>
                                <template v-else>
                                    <video :src="scope.row.filePath" width="300" controls="controls">
                                        您的浏览器不支持 video 标签。
                                    </video>
                                </template>
                            </template>
                        </el-table-column>
                        <el-table-column label="路徑">
                            <template scope="scope">
                                <span>{{scope.row.filePath}}</span>
                            </template>
                        </el-table-column>
                        <el-table-column label="標題" align="center">
                            <template scope="scope">
                                <span>{{scope.row.fileTitle}}</span>
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" width="150" align="center">
                            <template scope="scope">
                                <el-button size="small" @click="editMedia(scope.$index, scope.row)">編輯</el-button>
                                <el-button size="small" type="danger" @click="deleteMedia(scope.$index, scope.row)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
            </section>
        </div>
    </div>
</template>
<script>
export default {
    components: {},
    mounted() {
        this.init();
    },
    data() {
        return {
            columnId: '',
            columnName: '',
            // 0 文章列表 1 圖片與影片
            columnType: '',
            columnTreeData: [],
            defaultProps: {
                children: 'children',
                label: 'columnName'
            },
            articleList: [],
            pager: {
                pageSize: 20,
                pageNum: 1,
                total: 0
            },
            activeName: 'type',
            mediaList: []
        };
    },
    computed: {
        hrefOfAddArticle() {
            let pathStart = this.columnType ? '/pic' : '/article';
            return pathStart + '?columnId=' + this.columnId + '&columnName=' + this.columnName;
        },
        nameOfAddArticle() {
            return this.columnType ? '添加文件' : '添加文章';
        }
    },
    watch: {
        columnId(val) {
            this.$router.replace({
                query: {
                    columnId: val
                }
            });
            this.pager.pageNum = 1;
            if (+this.columnType === 1) {
                this.getMediasByColumnId();
            }
            else {
                this.getArticles();
            }
        }
    },
    methods: {
        init() {
            this.getColumnTree().done(() => {
                this.$nextTick(() => {
                    let columnId = +this.$route.query.columnId;
                    if (columnId) {
                        this.initDefaultActive(columnId);
                    }
                    else if (this.columnTreeData.length > 0) {
                        this.columnId = this.columnTreeData[0].id;
                        this.columnName = this.columnTreeData[0].columnName;
                        this.columnType = this.columnTreeData[0].columnType;
                    }
                });
            });
        },
        initDefaultActive(columnId) {
            let columnData = this.getColumnFromTreeDataById(columnId);
            if (columnData) {
                this.columnId = columnData.id;
                this.columnName = columnData.columnName;
                this.columnType = columnData.columnType;
            }
        },

        /**
         * 根据栏目ID获得栏目名称,从栏目树立获取，需要递归，写的不好，以后重新处理
         * @param  {String} columnId 栏目ID
         * @return {String}          栏目名称
         */
        getColumnFromTreeDataById(columnId) {
            function getColumn(id, array) {
                let result = false;
                array.every(item => {
                    if(item.id === id) {
                        result = item;
                        return false;
                    }
                    if (item.children && item.children.length > 0) {
                        result = getColumn(id, item.children);
                        if (result !== false) {
                            return false;
                        }
                    }
                    return true;
                });
                return result;
            }
            return getColumn(columnId, this.columnTreeData) || '';
        },

        getColumnTree() {
            return $.request('/column/getColumnTrees.do').then(res => {
                this.columnTreeData = res.data;
            });
        },
        /**
         * 获得文章
         */
        getArticles() {
            let url = '/article/getArticlesByColumnId.do';
            let data = $.extend({columnId: this.columnId}, this.pager);
            delete data.total;
            return $.request(url, {
                data: data
            }).then(res => {
                this.articleList = res.data.list;
                this.pager.total = res.data.total;
            });
        },
        getMediasByColumnId() {
            let url = '/media/getMediasByColumnId.do';
            return $.request(url, {
                data: {columnId: this.columnId}
            }).then(res => {
                this.mediaList = res.data.list;
            });
        },
        handleSizeChange(val) {
            this.pager.pageSize = val;
            this.getArticles();
        },
        handleCurrentChange(val) {
            this.pager.pageNum = val;
            this.getArticles();
        },
        handleTreeNodeClick(row, node) {
            this.columnId = row.id;
            this.columnName = row.columnName;
            this.columnType = row.columnType;
        },
        /**
         * 编辑文章页跳转
         */
        handleEdit(index, row) {
            this.$router.push({
                path: 'article',
                query: {
                    articleId: row.id,
                    columnId: row.columnId
                }
            });
        },
        /**
         * 删除文章
         * @param  {Number} index 数据索引
         * @param  {Object} row   当前行所有数据
         */
        deleteArticle(index, row) {
            let me = this;
            function doDelete() {
                return $.request('/article/deleteArticleById.do', {
                    method: 'post',
                    data: {
                        id: row.id
                    }
                });
            }
            function deleteSuccess() {
                me.$message('刪除成功');
                me.articleList.splice(index, 1);
            }
            this.$alert('確定刪除該文章嗎？', '提示', {
                confirmButtonText: '確定',
                callback() {
                    doDelete().then(deleteSuccess);
                }
            });
        },
        editMedia(index, row) {
            this.$router.push({
                path: 'pic',
                query: {
                    mediaId: row.id,
                    columnId: row.columnId,
                    fileTitle: row.fileTitle
                }
            });
        },
        deleteMedia(index, row) {
            let me = this;
            function doDelete() {
                return $.request('/media/deleteMediaById.do', {
                    method: 'post',
                    data: {
                        id: row.id
                    }
                });
            }
            function deleteSuccess() {
                me.$message('刪除成功');
                me.mediaList.splice(index, 1);
            }
            this.$alert('確定刪除該文件嗎？', '提示', {
                confirmButtonText: '確定',
                callback() {
                    doDelete().then(deleteSuccess);
                }
            });
        },
        filterNode(value, data, node) {
            console.log(123);
        },
        testPic(str) {
            return /\.(jpg|gif|png)$/.test(str.toLocaleLowerCase());
        }
    }
}
</script>
<style lang="less">
.article-mng {
    .content {
        display: flex;
        nav {
            flex: 0 0 200px;
        }
        section {
            flex: 1;
            overflow: hidden;
            padding-left: 20px;
        }
    }
    .article-list {
        margin-top: 0;
        li {
            font-size: 14px;
            line-height: 24px;
        }
        a:hover {
            text-decoration: underline;
        }
    }
    .el-pagination {
        text-align: right;
        margin-top: 10px;
    }
    .el-tree--highlight-current .el-tree-node.is-current>.el-tree-node__content {
        background-color: #ddd;
    }
    .media {
        img {
            max-width: 200px;
            margin: 14px 0;
        }
    }
    .media-list {
        table {
            max-width: 100% !important;
            width: 100% !important;
        }
        img, video {
            max-width: 100%;
            margin: 10px 0;
        }
    }
}
</style>
